/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.common;

import com.mxg.blog.entity.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/22 18:29
 * 创建token
 */
public class CreatToken {
    /**
     * 创建 token
     *
     * @param user 用户信息
     * @return token
     */
    public String createToken(User user) {
        Date now = new Date();
        //设置过期时间为4小时
        Date expireTime = new Date(now.getTime() + 60 * 60 * 1000 * 4);

        //添加 token 使用的秘钥
        String secretKey = "MxgGetTokenSignatureAlgorithm123456789111213!@#$%";
        //生成 token
        String token = Jwts.builder().setId(user.getId().toString())
                .setSubject(user.getUserName()).setIssuedAt(now)
                .setExpiration(expireTime).signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();

        return token;
    }
}
